<template>
    <el-form-item :label="label">
        <div v-if="scoped" class="grid">
            <template v-for="n in 2" :key="n">
                <component :is="is" v-model="data![n-1]" :class="{scoped:n==1}" v-bind="sonAttrs"/>
            </template>
        </div>
        <component v-else :is="is" v-model="data" v-bind="sonAttrs">
            <template #prepend v-if="sonAttrs.slots?.['prepend']!=null">{{sonAttrs.slots['prepend']}}</template>
        </component>
    </el-form-item>
</template>
<script setup lang="ts">
import { ref,computed,useAttrs,watch } from 'vue'
const value = defineModel()
const attrs = useAttrs()
const {label,type,scoped} = defineProps<{
    label:string
    type?:'number'|'text'
    /**是否展示范围 */
    scoped?:boolean
}>()

defineOptions({inheritAttrs: false})
const inputType = computed(()=>{
    if(type==='number'||scoped)return 'number'
    return 'text'
})
const is = computed(()=>inputType.value === 'number'?'el-input-number':'el-input')

const sonAttrs = computed(()=>{
    let attr = {...attrs}
    //数字输入框
    if(inputType.value=='number'){
        //默认按钮位置在右侧
        if(!('controlsPosition' in attr))attr['controlsPosition'] = 'right';
        if(typeof value.value!='number'){
            let val = Number(value.value);
            value.value = isNaN(val)?0:val;
        }
    }
    return attr
})
const data = ref(defaultValue())
if(scoped)watch(data,val=>value.value = JSON.parse(JSON.stringify(val)),{deep:true});
else watch(data,val=>value.value = val);
watch(value,val=>{
    if(scoped){
        if(Array.isArray(val))data.value = val;
        else{
            try {
                data.value = JSON.parse(val as string)
            } catch (e) {}
        }
    }
    else {
        if(inputType.value=='number'){
            let e = Number(val);
            if(!isNaN(e))data.value = e;
        }
        else data.value = val||'';
    }
});
watch(()=>scoped,()=>data.value = defaultValue())
/**返回默认值 */
function defaultValue(){
    let result;
    if(scoped)result = Array.isArray(value.value)?value.value:[];
    else {
        if(inputType.value=='text'){
            if(typeof value.value=='string')result = value.value;
            else if(value.value)result = value.value.toString();
            else result = '';
        }
        else if(inputType.value=='number'){
            let val = Number(value.value);
            result = isNaN(val)?0:val;
        }
    }
    return result;
}
</script>
<style scoped>
.el-input-number{
    width:100%;
}
.grid{
    width: 100%;
    display: grid;
    grid-template-columns: calc(50% - 15px) calc(50% - 15px);
    gap: 30px;
}
.el-input.scoped::after,.el-input-number.scoped::after{
    content:"~";
    position: absolute;
    right: -20px;
}
:deep(.el-input-group__prepend){
    padding: 0 10px;
}
</style>